/*

 需要引用jquery 和 jquery.form.min.js
	
 <!- -默认的上传form表单，页面中不写的话，js会自动生成，但是ie8上，js生成的form无法提交 -->
 <form method="POST" style="position: fixed; left: -10000px;" action="/Api/Upload/ajax_upload_file" id="upload-form"  enctype="multipart/form-data">
		<input type="file" id="file-upload-input" accept="image/jpg, image/jpeg" name="Filedata">
 </form>

 new Upload({
	elem: 'upload-btn-1',
	url: '/Api/Upload/ajax_upload_file',
	name: 'Filedata[]',
	formId: 'upload-form-1',
	inputId: 'upload-1',
	success: function(json) {
		console.log(this, 121312);
		console.log(this.btn, json);
	},
	error: function() {
		console.log('上传失败');
	}
});
*/

function Upload(opt) {
	opt = opt || {};
	this.opt = {
		default: true, 
		url: '/Api/Upload/ajax_more_img',
		elem: 'upload-btn', // 上传的按钮
		formId: 'upload-form', // form表单的id
		name: 'Filedata[]', // input file 的name 
		inputId: 'file-input', // input file 的id
		accept: '', // input的accept属性
		multiple: false, // 是否允许多选文件
		success: function() {},
		error: function() {},
		uploadProgress: function() {},
		beforeSubmit: function() {},
		beforeAjax: null, // 上传图片之前的执行的函数（点击上传按钮的时候触发），如果返回值为false， 将不会执行上传图片操作
	};

	this.btn = null;  // 上传按钮
	this.selectFileName = null; // 选择的文件的名称（现在后台会返回这个值，这个值没有用到）

	for (var key in this.opt) {
		if (key in opt) {
			this.opt[key] = opt[key];
		}
	}

	// opt.elem 不包含class或者id的前缀标识（. | #）
	var indexstr = this.opt.elem.substr(0, 1);
	if (indexstr == '.' || indexstr == '#') {
		this.opt.elem = this.opt.elem.slice(1, this.opt.elem.length - 1);
	}
	this.createForm();
}

/**
 * [createForm 创建form表单]
 * @param  {[type]} source [description]
 * @param  {[type]} arg    [description]
 * @return {[type]}        [description]
 */
Upload.prototype.createForm = function() {
	var form = document.getElementById(this.opt.formId),
		input = null;
	if (form) { 
		input = document.getElementById(this.opt.inputId);
	} else {
		form = document.createElement('form');
		form.action = this.opt.url;
		form.method = 'post';
		form.enctype = "multipart/form-data";
		form.style.position = 'fixed';
		form.style.left = -10000 + 'px';
		form.style.top = '50%';

		input = document.createElement('input');
		input.type = 'file';
		input.id = this.opt.inputId;
		input.name = this.opt.name;
		if (this.opt.accept) {
			input.accept = this.opt.accept;
		}
		input.multiple = this.opt.multiple ? 'multiple' : '';
		form.appendChild(input);
		document.body.appendChild(form);
	}

	this.bindBtnClick(input);
	this.inputBindChange(input, form);
};


/**
 * js绑定事件
 * @param  {[dom]}   elem   [被绑定事件的元素]
 * @param  {[string]} event [绑定的事件名称]
 * @param  {Function} fn    [事件触发执行的函数] 
 * @return {[type]}         [description]
 */
Upload.prototype.bindEvent = function(elem, event, fn) {
	if (elem.addEventListener) {
		elem.addEventListener(event, fn);
	} else if (elem.attachEvent) {
		elem.attachEvent('on' + event, fn);
	} else {
		elem['on' + event] = fn;
	}
};


/**
 * 为按钮绑定click事件， 为this.btn赋值
 * @param  {[type]} input [type file ]
 * @return {[type]}       [description]
 */
Upload.prototype.bindBtnClick = function(input) {
	var _this = this;

	this.bindEvent(document.body, 'click', function(e) {
		var ev = e || window.event,
			eventTarget = ev.target || ev.srcElement;

		while (eventTarget && eventTarget.nodeName.toUpperCase() !== 'BODY') {

			if (eventTarget.className.indexOf(_this.opt.elem) >= 0 || eventTarget.id == _this.opt.elem) {
				_this.btn = $(eventTarget); 

				if (_this.opt.beforeAjax && typeof _this.opt.beforeAjax == 'function') {

					if (!_this.opt.beforeAjax.call(_this)) {
						if (e.preventDefault) {
							e.preventDefault();
						} else {
							e.returnValue = false;
						}
						return true;
					}
				}

				if (!(eventTarget.nodeName.toUpperCase() == 'LABEL' && eventTarget.getAttribute('for') == _this.opt.inputId)) {
					input.click();
				}
				break;
			}

			eventTarget = eventTarget.parentNode;
		}
	});
};

/**
 * input type file绑定change事件
 * @param  {[Dom]}  elem [input]
 * @param  {[type]} form [description]
 * @return {[type]}      [description]
 */
Upload.prototype.inputBindChange = function(elem, form) {
	var _this = this;
		
	this.bindEvent(elem, 'change', function(e) {
		var name = $(this).val().split('\\'),
			opt = _this.getOption();

		_this.btn.disabled = true;
		_this.showLoading();
		_this.selectFileName = name[name.length - 1];
		$(form).ajaxSubmit(opt);
	});
};


/**
 * 获取ajax提交表单配置参数, 确保回调函数中使用的this指向当前Upload实例
 * @param  {[Upload]} _this [当前创建的Upload实例]
 * @return {[Object]}       [ajax提交表单配置参数]
 */
Upload.prototype.getOption = function() {
	var _this = this,
		type;


	if (this.btn) {
		type = this.btn.data('type') || 'img'; // file 或者 img, 默认img
	}

	function success(json) {
		_this.btn.disabled = false;
		_this.hideLoading();
		
		_this.opt.success.call(_this, json, _this.selectFileName);
		if (!_this.opt.default) {	
			return;
		}

		if (type == 'img') {
			_this.defaultImgSuccess.call(_this, json);
		} else {
			_this.defaultFileSuccess.call(_this, json);
		}
	}

	function error() {
		_this.btn.disabled = true;
		_this.hideLoading();
		_this.opt.error.call(_this);
	}

	function uploadProgress(n) {
		_this.opt.uploadProgress.call(_this, n);
	}

	function beforeSubmit() {
		_this.opt.beforeSubmit.call(_this);
	}

	return {
		success: success, //提交后的回调函数  
		error: error,
		beforeSubmit: beforeSubmit,
		uploadProgress: uploadProgress,
		dataType: 'json', //html(默认), xml, script, json...接受服务端返回的类型  
		clearForm: true, //成功提交后，清除所有表单元素的值  
		resetForm: true, //成功提交后，重置所有表单元素的值  
		timeout: 10000 //限制请求的时间，当请求大于10秒后，跳出请求  
	};
};

/**
 * 默认上传图片成功之后的回调
 * @param  {[type]} json [description]
 * @return {[type]}      [description]
 */
Upload.prototype.defaultImgSuccess = function(json) { 
	var str = '',
		name = this.btn.data('name'),
		replace = this.btn.data('replace');

	$.each(json.data, function(n, val) {
		str += '<div class="list">'+
					'<img src="'+ val.url +'" alt="">'+
					'<div class="operate">'+
						'<i class="iconfont preview-img" style="left:30px;">&#xe615;</i>'+
						'<i class="iconfont delete-img">&#xe65f;</i>'+
					'</div>'+
					'<div class="musk"></div>'+
					'<input type="hidden" name="'+ name +'" value="'+ val.url +'">'+
				'</div>';
	});

	if (replace) {
		this.btn.siblings('.list').remove();
		this.btn.html('<span>修改</span>');
	}
	this.btn.before(str);

	
};

/**
 * 默认上传附件成功之后的回调
 * @param  {[ajax返回的数据]} json [description]
 * @return {[type]}      [description]
 */
Upload.prototype.defaultFileSuccess = function(json) { 
	var str = '',
		name = this.btn.data('name'),
		replace = this.btn.data('replace');

	$.each(json.data, function(n, val) {
		str += '<div class="list">'+
                	'<div class="detail">'+
                		'<div class="file-name">'+ val.name +'</div>'+
                		'<div class="status">'+
                			'<i class="hw-iconfont">&#xe650;</i>'+
                			'<i class="hw-iconfont delete-file">&#xe63d;</i>'+
                		'</div>'+
                	'</div>'+
                	'<a href="'+ val.url +'" class="hw-word-btn" download="'+ val.name +'">下载</a>'+
                	'<input type="hidden" name="'+ name +'" value="'+ val.url +'">'+
                '</div>';
	});

	if (replace) {
		this.btn.parents('.group-info').find('.hw-attachment-lists').html(str);
		return;
	}
	this.btn.parents('.group-info').find('.hw-attachment-lists').append(str);
};

// 默认上传失败的回调
Upload.prototype.defaultError = function(e) {
	$.alert('请求失败');
	console.error(e);
};


// 上传的时候显示蒙层
Upload.prototype.showLoading = function() {

	var elem = $('#upload-loading-wrap');

	if (elem.length > 0) {
		elem.removeClass('hide');
	} else {
		$('body').append('<div class="upload-loading-wrap" id="upload-loading-wrap"><div class="musk"></div><img src="/static/img/loading.gif"></div>');
	}
};

// 隐藏蒙层
Upload.prototype.hideLoading = function() {
	$('#upload-loading-wrap').addClass('hide');
};


$(function() {
	var imgModal = $('#img-modal'); // 预览图片模态框

	/* 附件删除 */
	$('.hw-attachment-lists').on('click', '.delete-file', function() {
		var _this = this;
		// 二次确认
		$.confirm('确认删除该附件吗？', function() {
			$(_this).parents('.list').remove();
		});
	});

	/* 图片删除 */
	$('body').on('click', '.hw-img-lists .delete-img', function() {
		var _this = this,
			btn = $(this).parents('.list').siblings('label');
		// 二次确认
		$.confirm('确认删除该图片吗？', function() {
			var btnLabel = $(_this).parents('.hw-img-lists').find('label');
			btnLabel.show();
			btnLabel.html('+');
			$(_this).parents('.list').remove();
			if (btn.siblings('.list').length <= 0) {
				btn.html('+');
			}
		});
	});

	// 图片预览
	$('body').on('click', '.hw-img-lists .preview-img', function () { 
		var imgurl = $(this).parents('.list').find('img').attr('src');
		createPreviewModal(imgurl); 
	});

	// 判断是否IE11, IE11的change事件会触发两次
	function isIEEleven(){
		if ("ActiveXObject" in window && window.navigator.userAgent.indexOf("MSIE") == -1) {
			return true;
		} else {
			return false;
		}
	}

	// 创建预览模态框
	function createPreviewModal(url) {
		var str;
		
		if (imgModal.length > 0) {
			imgModal.find('.modal-body').find('img').attr('src', url);
			imgModal.removeClass('hide');
			return;
		} 

		str = '<div class="modal hide" id="img-modal">'+
				    '<div class="modal-mask"></div>'+
				    '<div class="modal-content">'+
				        '<div class="modal-header">'+
				            '<i class="iconfont" data-dismiss="modal">&#xe63d;</i>'+
				            '<div class="modal-title">图片预览</div>'+
				        '</div>'+
				        '<div class="modal-body">'+
				        	'<img class="preview-img-box" src="'+ url +'">'+
				        '</div>'+ 
				    '</div>'+
				'</div>';
		$('body').append(str);
		setTimeout(function() {
			imgModal = $('#img-modal');
			imgModal.removeClass('hide');
		}, 20);
	}
});